package com.hj.authority.service.impl;

import cn.hutool.core.util.StrUtil;

import com.hj.authority.dao.SysMenuDao;
import com.hj.authority.domain.constant.AuthorityConstant;
import com.hj.authority.domain.convert.SysMenuConvert;
import com.hj.authority.domain.entity.SysMenu;
import com.hj.authority.domain.enums.SuperAdminEnum;
import com.hj.authority.domain.vo.SysMenuVO;
import com.hj.authority.service.SysMenuService;
import com.hj.authority.utils.TreeUtils;
import com.hj.mybatis.service.impl.BaseServiceImpl;
import com.hj.security.user.HjUserDetails;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author hj
 * @Date 2023/4/27
 * @Description: 菜单管理
 */
@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuDao, SysMenu> implements SysMenuService {

    @Resource
    private SysMenuDao sysMenuDao;

    @Override
    public List<SysMenuVO> getMenuList(Integer type) {
        List<SysMenu> menuList = sysMenuDao.getMenuList(type);
        List<SysMenuVO> sysMenuVOList = SysMenuConvert.INSTANCE.convertList(menuList);
        return TreeUtils.build(TreeUtils.build(sysMenuVOList, AuthorityConstant.ROOT));
    }

    @Override
    public List<SysMenuVO> getUserMenuList(HjUserDetails user, Integer type) {
        List<SysMenu> menuList;
        // 系统管理员，拥有最高权限
        if (user.getSuperAdmin().equals(SuperAdminEnum.YES.getValue())) {
            menuList = sysMenuDao.getMenuList(type);
        } else {
            menuList = sysMenuDao.getUserMenuList(user.getId(), type);
        }
        List<SysMenuVO> sysMenuVOList = SysMenuConvert.INSTANCE.convertList(menuList);
        return TreeUtils.build(sysMenuVOList);
    }


    @Override
    public Set<String> getUserAuthority(HjUserDetails user) {
        // 系统管理员，拥有最高权限
        List<String> authorityList;
        if (user.getSuperAdmin().equals(SuperAdminEnum.YES.getValue())) {
            authorityList = sysMenuDao.getAuthorityList();
        } else {
            authorityList = sysMenuDao.getUserAuthorityList(user.getId());
        }
        // 用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String authority : authorityList) {
            if (StrUtil.isBlank(authority)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(authority.trim().split(",")));
        }
        return permsSet;
    }


}